package com.gzdcdata.xxorder.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gzdcdata.core.common.ApiController;
import com.gzdcdata.core.common.CusAccessObjectUtil;
import com.gzdcdata.core.common.ResponseData;
import com.gzdcdata.xxorder.entity.XxOrderDetail;
import com.gzdcdata.xxorder.service.XxOrderService;
import com.gzdcdata.xxorderitem.entity.XxOrderItem;
import com.gzdcdata.xxproduct.entity.XxProduct;
import com.wxpay.gzdcdata.pay.WXPayUtil;

/**
 * 订单处理控制器
 * @author dsj
 *
 *
 */
@Controller
@RequestMapping("/xxorder")
public class XxOrderController extends ApiController {

	@Resource(name="xxOrderService")
	private XxOrderService xxOrderService;


	/**
	 * 网页内请求生成未支付订单
	 * @param addrId 地址信息
	 * @param memo  备注信息
	 * @param shopList 商品信息
	 * @return
	 */
	@PostMapping("/initOrderInfo")
	public ResponseEntity<ResponseData> initOrderInfo(Long userId,Long addrId,String memo,String shopList,HttpServletRequest request){
		logger.info("订单提交");
        try {
        	ObjectMapper objectMapper = new ObjectMapper();
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, XxProduct.class);
			List<XxProduct> list = objectMapper.readValue(shopList, javaType);
			String sn=xxOrderService.insertOrder(userId,addrId,memo,list,CusAccessObjectUtil.getIpAddress(request));
			logger.info("订单sn"+sn);
			return new ResponseEntity<ResponseData>(success(sn),HttpStatus.OK);
		} catch (JsonParseException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		} catch (JsonMappingException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			logger.error("服务层添加或处理数据出错！"+e.getMessage());
			e.printStackTrace();
		}
        return new ResponseEntity<ResponseData>(fail("订单初始化失败！"),HttpStatus.BAD_REQUEST);
	}
	 /**
	  * 生成微信商户订单
	  */
	@PostMapping("/payOrder")
	public ResponseEntity<ResponseData> payOrder(String paymentSn,HttpServletRequest request, String payOpenid){
		//String code=request.getParameter("code");
		logger.info("用户点击付款 payOpenid"+payOpenid+"付款单号paymentSn"+paymentSn);
		if(payOpenid==null||payOpenid.trim()==""){
			 return new ResponseEntity<ResponseData>(fail("payOpenid参数错误！"),HttpStatus.BAD_REQUEST);
		}
		if(paymentSn==null||paymentSn.trim()==""){
			 return new ResponseEntity<ResponseData>(fail("参数错误！"),HttpStatus.BAD_REQUEST);
		}
		try {
			logger.info("用户支付"+CusAccessObjectUtil.getIpAddress(request));
			Map<String, String> map=xxOrderService.payOrder(paymentSn,CusAccessObjectUtil.getIpAddress(request),payOpenid);
	        return new ResponseEntity<ResponseData>(success(map),HttpStatus.OK);
		} catch (Exception e) {
			e.printStackTrace();
			 return new ResponseEntity<ResponseData>(fail(e.getMessage()),HttpStatus.BAD_REQUEST);
		}
	}

	/**
	 *
	* 分页查询订单
	 * @param order_status 订单状态
	 * @param userId 用户id
	 * @param page
	 * @param rows
	 * @return
	 */
	@PostMapping("/listByStatusAndUser")
	public ResponseEntity<ResponseData> listByStatusAndUser(Integer order_status,Long userId,
			@RequestParam(name="page",defaultValue="0")  Integer page,
			@RequestParam(name="rows",defaultValue="10")  Integer rows){
		if(order_status==null||userId==null){
	        return new ResponseEntity<ResponseData>(fail("参数不正确！"),HttpStatus.BAD_REQUEST);
		}
		try{
			List<XxOrderDetail> list=xxOrderService.listByStatusAndUser(order_status,userId,page,rows);
			return new ResponseEntity<ResponseData>(success(list),HttpStatus.OK);
		}catch (Exception e) {
	        return new ResponseEntity<ResponseData>(fail("查询错误！"),HttpStatus.BAD_REQUEST);
		}
	}
	/**
	 * 取消待付款的订单
	 * @param userId
	 * @param orderId
	 * @return
	 */
	@GetMapping("/cancelOrder")
	public ResponseEntity<ResponseData> cancelOrder(String userId,String sn){
		try {
			xxOrderService.cancelOrder(userId,sn);
			return new ResponseEntity<ResponseData>(success("取消成功!"),HttpStatus.OK);
		} catch (Exception e) {
			logger.error("订单取消:"+e.getMessage());
		}
        return new ResponseEntity<ResponseData>(fail("参数等原因导致的取消失败！"),HttpStatus.BAD_REQUEST);
	}
	/**
	 * 获取订单详情信息
	 * @param sn
	 * @param memberId 用户id
	 * @return
	 */
	@PostMapping("/getOrderDetatil")
	public ResponseEntity<ResponseData> getOrderDetatil(String sn,String memberId){
		if("".equals(sn)||sn==null|| "".equals(memberId)||memberId==null){
	        return new ResponseEntity<ResponseData>(fail("参数不正确！"),HttpStatus.BAD_REQUEST);
		}
		XxOrderDetail xxOrderDetail=xxOrderService.getOrderDetatil(sn,memberId);
		if(xxOrderDetail==null){
	        return new ResponseEntity<ResponseData>(fail("未查询到相关订单信息！"),HttpStatus.BAD_REQUEST);
		}
		return new ResponseEntity<ResponseData>(success(xxOrderDetail),HttpStatus.OK);
	}
	/**
	 * 订单支付成功  该接口用于微信回调
	 * 更新订单表的状态
	 * @param paymentId
	 * @return
	 */
	@RequestMapping("/paySuccess")
	@ResponseBody
	public String paySuccess(HttpServletRequest request){
		logger.info("微信回调连接更新付款单状态");
		//返回
		Map<String, String> resultMap = new HashMap<String,String>();
		try {
		//获取返回成功的信息去更新订单状态
		InputStream inputStream = request.getInputStream();
		StringBuffer sb=new StringBuffer();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = in.readLine()) != null) {
			sb.append(s);
		}
		//接收结果
		Map<String, String> map = WXPayUtil.xmlToMap(sb.toString());

		resultMap=xxOrderService.paySuccess(map,1);

		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("return_code","FAIL");
			resultMap.put("return_msg","操作失败!");
		}
		logger.info("微信回调结果"+resultMap);
			try {

				return WXPayUtil.mapToXml(resultMap);
			} catch (Exception e) {
				e.printStackTrace();
				return "<xml><return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[操作失败]]></return_msg>"
						+ "</xml>";
			}
	}
	/**
	 * 确认收货 TODO 暂时更新状态为2 即为待评价商品
	 * @param userId
	 * @param sn
	 * @return
	 */
	@RequestMapping("/acceptOk")
	public ResponseEntity<ResponseData> acceptOk(String userId,String sn){
		try {
			xxOrderService.acceptOk(userId,sn);
			return new ResponseEntity<ResponseData>(success("取消成功!"),HttpStatus.OK);
		} catch (Exception e) {
			logger.error("订单取消:"+e.getMessage());
		}
        return new ResponseEntity<ResponseData>(fail("操作失败！"),HttpStatus.BAD_REQUEST);
	}

	/**
	 * 通过订单编号获取该订单下面的产品快照信息
	 * @param memberId 暂时没用
	 * @param sn 订单编号
	 * @return
	 */
	@RequestMapping("/getProductByOrderSn")
	public ResponseEntity<ResponseData> getProductByOrderSn(String memberId,String sn){
		if(sn==null||sn.trim()==""){
	        return new ResponseEntity<ResponseData>(fail("参数不能为空！"),HttpStatus.BAD_REQUEST);
		}
		List<XxOrderItem> list =xxOrderService.getProductByOrderSn(sn);
		if(list!=null&&list.size()>0){
			return new ResponseEntity<ResponseData>(success(list),HttpStatus.OK);
		}else{
	        return new ResponseEntity<ResponseData>(fail("参数错误！"),HttpStatus.BAD_REQUEST);
		}
	}
}
